// 2013-10-2上午11:29:52  net.betou.web.ProxyToShowAgencyDirective.java

package net.betou.web;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import net.betou.common.util.DataConvertUtils;
import net.betou.trade.entity.main.AgentAndAdmins;
import net.betou.trade.main.manager.agencyorproxy.AgencyMng;
import net.betou.web.freemaker.DirectiveUtils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 代理商页面显示上级机构标签
 * @author 叶装装
 */
public class ProxyToShowAgencyDirective implements TemplateDirectiveModel{

	public static final String PARAM_AGENCY = "agency"; // 是否是机构，如果是的话，就直接返回, 传入的参数为当前代理商的上级
	public static final String PARAM_NAME = "agencyName"; // 机构的名称, 传入的参数为当前代理商的上级
	public static final String PARAM_TOP_INTERMEDIA = "top_intermedia"; // 上级的 
	
	@SuppressWarnings( "unchecked" )
	public void execute( Environment env, Map params, TemplateModel [ ] loopVars, TemplateDirectiveBody body ) throws TemplateException, IOException {

		Boolean isAgency = DirectiveUtils.getBool( PARAM_AGENCY, params );
		String name =DirectiveUtils.getString( PARAM_NAME, params );
		
		if( !isAgency ){
			// 循环topIntermedia
			String [ ] topIntermedia = StringUtils.split(  DirectiveUtils.getString( PARAM_TOP_INTERMEDIA, params ), "," );
			
			if( topIntermedia != null && topIntermedia.length > 0 ){
				for( int i = topIntermedia.length - 1 ; i >= 0; i-- ){
					AgentAndAdmins admin = mng.findById( DataConvertUtils.getInt( topIntermedia[ i ] ) );
					if( admin.getAgencyOrProxy( ) ){
						name = admin.getIntermediaName( );
						break;
					}
				}
			}
		}

		Writer out = env.getOut( );
		out.append( name );
	}
	
	@Autowired
	private AgencyMng mng;
	
}
